#include "../include/socketIO.h"
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>

SocketIO::SocketIO(int fd)
:_fd(fd)
{

}

SocketIO::~SocketIO()
{
	close(_fd);
}

int SocketIO::readn(char * buf,int len)
{
	int left = len;
	char * pstr = buf;
	int ret = 0;
	
	while(left > 0)
	{
		ret = read(_fd,buf,left);
		if(ret == -1 && errno == EINTR)
			continue;
		else if(ret == -1)
		{
			perror("read error -1");
			return -1;
		}
		else if(ret == 0)
			break;
		else
		{
			left -= ret;
			pstr = pstr + ret;
		}
	}
	
	return len - left;
}

int SocketIO::readLine(char * buf,int len)
{
	int left = len - 1;
	char * pstr = buf;
	int ret = 0,total = 0;

	while(left > 0)
	{
		// 不会清空缓冲区，相当于查看缓冲区中的数据
		ret = recv(_fd,buf,left,MSG_PEEK);
		if(ret == -1 && errno == EINTR)
			continue;
		else if(ret == 0)
			break;
		else if(ret == -1)
		{
			perror("readLine error -1");
			return -1;
		}
		else
		{
			for(int i = 0;i < ret;i++)
			{
				// 如果有多行数据
				if(pstr[i] == '\n')
				{
					int next = i + 1;
					readn(pstr,next);
					pstr += next;
					*pstr = '\0';

					return total + next;
				}
			}
			// 仅有一行数据
			readn(pstr,ret);
			total += ret;
			pstr += ret;
			left -= ret;
		}
	}
	*pstr = '\0';

	return total - left;

}

int SocketIO::writen(const char * buf,int len)
{
	int ret = 0,left = len;
	const char * pstr = buf;

	while(left > 0)
	{
		ret = write(_fd,pstr,left);
		if(ret == -1 && errno == EINTR)
			continue;
		else if(ret == -1)
		{
			perror("wriite error -1");
			return -1;
		}
		else if(ret == 0)
			break;
		else
		{
			pstr += ret;
			left -= ret;
		}
	}
	return len - left;

}


